#include <omnetpp.h>
#include "DataStation.h"
#include "DATAPacket_m.h"
#include "IPv4Address.h"

Define_Module(DataStation);

void DataStation :: initialize() {
    numReceivedSum = 0;
    WATCH_MAP(numReceived);
}

void DataStation :: handleMessage(cMessage *msg) {
    DataPacket *dataPacket = dynamic_cast<DataPacket *>(msg);
    if (dataPacket) {
        handleIncomingPacket(dataPacket);
    }
    else {
        EV << "Hien Hoang: Unknown packet, discarding... "<< endl;
        delete msg;
    }
}

void DataStation :: handleIncomingPacket(DataPacket *pkt) {

    IPv4Address& src = pkt->getSrcAddr();
    if (pkt->getDType() == DATAREQ) {
        if (numReceived.find(src) != numReceived.end())
        {
            numReceived[src]++;
        }
        else
        {
            numReceived[src] = 1;
        }
        numReceivedSum++;
        updateNodeDisplay();
        EV << "Received " << numReceived[src] <<"packet from " << src.str() << endl;
    }
    delete pkt;
}

void DataStation :: updateNodeDisplay() {
    if (getParentModule()->isEvEnabled()) {
       char buf[40];
       sprintf(buf, "Recv: %ld", numReceivedSum);
       getParentModule()->getDisplayString().setTagArg("t",0,buf);
   }
}
